package com.socialsoftware.MediaCommunication.activity;

import android.content.Intent;
import android.os.Bundle;
import android.widget.Button;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.permissionx.guolindev.PermissionX;
import com.socialsoftware.MediaCommunication.model.CallMode;
import com.socialsoftware.MediaCommunication.service.CallService;
import com.socialsoftware.MediaCommunication.service.WebSocketService;
import com.socialsoftware.MediaCommunication.utils.Constants;
import com.socialsoftware.R;

public class HomeActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);

        // Check permissions and start services
        checkPermissionsAndStartServices();

        // 初始化按钮并设置点击事件
        Button btnVideoCall = findViewById(R.id.btn_video_call);
        Button btnVoiceCall = findViewById(R.id.btn_voice_call);
        Button btnScreenShare = findViewById(R.id.btn_screen_share);

        // 视频通话按钮点击事件
        btnVideoCall.setOnClickListener(v -> {
            // 跳转到视频通话页面
            Intent intent = new Intent(HomeActivity.this, VideoChatActivity.class);
            intent.putExtra(Constants.EXTRA_CALL_MODE, CallMode.VIDEO.getValue());
            startActivity(intent);
        });

        // 语音通话按钮点击事件
        btnVoiceCall.setOnClickListener(v -> {
            // 跳转到语音通话页面
            Intent intent = new Intent(HomeActivity.this, AudioChatActivity.class);
            intent.putExtra(Constants.EXTRA_CALL_MODE, CallMode.AUDIO.getValue());
            startActivity(intent);
        });
        
        // 屏幕共享按钮点击事件
        btnScreenShare.setOnClickListener(v -> {
            // 跳转到屏幕共享页面
            Intent intent = new Intent(HomeActivity.this, ScreenSharingActivity.class);
            intent.putExtra(Constants.EXTRA_CALL_MODE, CallMode.SCREEN.getValue());
            startActivity(intent);
        });
    }

    private void checkPermissionsAndStartServices() {
        PermissionX.init(this)
                .permissions(Constants.REQUIRED_PERMISSIONS)
                .request((allGranted, grantedList, deniedList) -> {
                    if (allGranted) {
                        // Start the WebSocket service
                        Intent webSocketServiceIntent = new Intent(this, WebSocketService.class);
                        startService(webSocketServiceIntent);
                        
                        // Start the Call service
                        Intent callServiceIntent = new Intent(this, CallService.class);
                        startService(callServiceIntent);
                    } else {
                        Toast.makeText(this, "需要相机和麦克风权限才能进行通话", Toast.LENGTH_SHORT).show();
                    }
                });
    }
}